using BasicData.API.Application.Command;
using BasicData.API.Dtos;
using BasicData.Domain.Entities;
using BasicData.ErrorCode;
using BasicData.Infrastructure.Interfasce;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace BasicData.API.Application.CommandHandlers
{
    /// <summary>
    /// 根据ID获取生产信息命令处理器
    /// </summary>
    public class GetProductionInfoByIdCommandHandler : IRequestHandler<GetProductionInfoByIdCommand, APIResult<ProductionInfoWithGoodsDTO>>
    {
        private readonly IBaseRepositroy<ProductionInfo> _productionInfoRepository;
        private readonly IBaseRepositroy<Goods> _goodsRepository;
        private readonly ILogger<GetProductionInfoByIdCommandHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="productionInfoRepository">生产信息仓储</param>
        /// <param name="logger">日志</param>
        public GetProductionInfoByIdCommandHandler(
            IBaseRepositroy<ProductionInfo> productionInfoRepository,
            IBaseRepositroy<Goods> goodsRepository,
            ILogger<GetProductionInfoByIdCommandHandler> logger)
        {
            _productionInfoRepository = productionInfoRepository;
            _goodsRepository = goodsRepository;
            _logger = logger;
        }

        /// <summary>
        /// 处理获取单个生产信息命令
        /// </summary>
        /// <param name="request">命令请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>生产信息</returns>
        public async Task<APIResult<ProductionInfoWithGoodsDTO>> Handle(GetProductionInfoByIdCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始获取生产信息，ID：{Id}", request.Id);

                // 使用 LINQ Join 查询生产信息和商品信息
                var productionInfoDTO = await (from p in _productionInfoRepository.GetAllAsync()
                                             join g in _goodsRepository.GetAllAsync() on p.GoodsId equals g.GoodsId
                                             where p.Id == request.Id && !p.IsDeleted
                                             select new ProductionInfoWithGoodsDTO
                                             {
                                                 Id = p.Id,
                                                 BatchNumber = p.BatchNumber,
                                                 ShelfLifeDays = p.ShelfLifeDays,
                                                 ProductionLicenseNumber = p.ProductionLicenseNumber,
                                                 ManufacturerName = p.ManufacturerName,
                                                 CoverImageUrl = p.CoverImageUrl,
                                                 GoodsId = p.GoodsId,
                                                 GoodsName = g.GoodsName,
                                                 CreatedTime = p.CreatedTime,
                                                 ModifiedTime = p.ModifiedTime
                                             }).FirstOrDefaultAsync(cancellationToken);

                if (productionInfoDTO == null)
                {
                    _logger.LogWarning("生产信息不存在或已删除，ID：{Id}", request.Id);
                    return new APIResult<ProductionInfoWithGoodsDTO>
                    {
                        Code = ResultCode.查询失败,
                        Message = $"生产信息不存在或已删除，ID：{request.Id}"
                    };
                }

                _logger.LogInformation("成功获取生产信息，ID：{Id}", request.Id);

                return new APIResult<ProductionInfoWithGoodsDTO>
                {
                    Code = ResultCode.查询成功,
                    Message = "获取生产信息成功",
                    Data = productionInfoDTO
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取生产信息时发生错误，ID：{Id}", request.Id);
                return new APIResult<ProductionInfoWithGoodsDTO>
                {
                    Code = ResultCode.查询失败,
                    Message = $"获取生产信息失败: {ex.Message}"
                };
            }
        }
    }
} 
